<?php
session_start();
require 'db_connect.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    die(json_encode(['success' => false, 'error' => '无效请求方法']));
}

$userID = $_SESSION['userId'];
if (!$userID) {
    http_response_code(401);
    die(json_encode(['success' => false, 'error' => '未登录']));
}

$data = json_decode(file_get_contents('php://input'), true);
$newPassword = $data['newPassword'] ?? '';

// 密码强度检查
if (strlen($newPassword) < 8) {
    die(json_encode(['success' => false, 'error' => '密码至少需要8位']));
}

// 生成新哈希
$hashedPassword = password_hash($newPassword, PASSWORD_BCRYPT);

// 更新数据库
$stmt = $conn->prepare("UPDATE User SET Password = ? WHERE UserID = ?");
$stmt->bind_param("si", $hashedPassword, $userID);

if ($stmt->execute()) {
    echo json_encode(['success' => true]);
} else {
    echo json_encode(['success' => false, 'error' => '数据库更新失败']);
}